
var ArticleComment = {
    params:{
        objectid:0, //article id
        objecttype:1, //1: article
        cateid:0,
        commentid:0,
        userid:0,
        siteid:0, //site id
        offset:0,
        limit: 10
    },
    totalComment:0,
    fullname:'',
    email:'',
    getComment:function(){
        
        //default options   
        var options = {
            data: ArticleComment.params,
            beforeSend:function(){
                $('.loading').show()
            },
            success: function(response){
                if(!response.error){
                    
                    ArticleComment.params.userid = response.data.userid;

                    if(response.data.total > 0){
                        ArticleComment.totalComment = response.data.total;
                        
                        //show total comment
                        $('#total_comment').text(ArticleComment.totalComment);

                        //show page detail comment
                        $('#comment_page_detail_wrapper').show();
                        var range  = ArticleComment.params.offset + ArticleComment.params.limit;
                        $('#comment_page_detail').text( (ArticleComment.params.offset +1) + ' - ' + ( range > ArticleComment.totalComment ? ArticleComment.totalComment:range));

                        //reset comment list
                        if(!ArticleComment.params.offset){
                            $('#list_comment').html('');
                        }

                        //append with template
                        $('#list_comment').jqoteapp('#tpl_comment_item', response.data);

                        //count remain comment to show more
                        var remain_comment = response.data.total - (this.data.limit + this.data.offset);
                        var totalPage = (Math.ceil(ArticleComment.totalComment/ArticleComment.params.limit));
                        var currentPage = ((ArticleComment.params.offset + ArticleComment.params.limit)/ArticleComment.params.limit-1);                        
                        var previousPage = (currentPage == 0) ? currentPage : currentPage - 1;                        
                        var nextPage = (currentPage == (totalPage - 1)) ? currentPage : currentPage + 1;
                        $('#cmt-paginator').jqotesub('#tpl_comment_showmore',{                            
                            items : {
                                total: ArticleComment.totalComment,
                                limit: ArticleComment.params.limit,
                                remain: remain_comment,
                                currentPage: currentPage,
                                previousPage: previousPage,
                                nextPage: nextPage,
                                totalPage: totalPage
                            }
                        });
                    }
                }
            },
            complete: function(){
                FPT_widget_mix();
                $('.loading').hide();
            },
            error:function(code, msg){}
        };
        
        //get first page
        Comment.get(options);

        $(document).on('click','.cmt-paginator',function(){
            $('#list_comment').html('');
            ArticleComment.params.offset = (ArticleComment.params.limit * Number(this.getAttribute('data-comment-page')));            
            Comment.get(options);
        });  
                      
    },
    renderAllReplies: function(data){
        $('#comment_replies_'+data.parentid).jqotesub('#tpl_comment_allreply', {
            items:data.data
        });
    },
    prependComment:function(data){
        $('#list_comment').jqotepre('#tpl_comment_prepitem', {
            item:data
        });
    },
    appendReply: function(target, data){        
        $('#'+target).find('.replys-wrapper').jqoteapp('#tpl_comment_item_reply', {
            item:data
        });
    },
    eventChangeTab: function(){
        $(document).on('click','.tab1',function(){
            $(this).addClass('active');
            $(this).parent().find('.tab2').removeClass('active');
            $(this).parent().next().find('#fptid_form').hide();
            $(this).parent().next().find('#guest_form').show();
        });

        $(document).on('click','.tab2',function(){
            $(this).addClass('active');
            $(this).parent().find('.tab1').removeClass('active');
            $(this).parent().next().find('#fptid_form').show();
            $(this).parent().next().find('#guest_form').hide();
        });
    },
    eventGuestSubmit: function(){
        $(document).on('click','#bt_finish',function(){   
            var form = $('#lightbox').find('#guest_form'), content;
            var emailInput = form.find('#txt_email');
            var email  = $.trim(emailInput.val());
            var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
            if(!pattern.test(email)){
                emailInput.next().html('Địa chỉ email không hợp lệ');
                return false;
            }else{
                emailInput.next().html('');
            }

            var fullname = $.trim(form.find('#txt_fullname').val());
            if(fullname==""){
                var posat = email.indexOf('@', 0);
                fullname = email.substring(0,posat);
            }

            Lightbox.hide();

            if(ArticleComment.type=='act_comment'){
                content = $.trim($('#comment_content').val());
            }else if(ArticleComment.type=='act_reply'){
                content = $.trim($('#comment_reply_content').val());
            }

            ArticleComment.addComment(content, fullname, email, ArticleComment.type);

            return true;
        });

        $(document).on('keyup','#lightbox #txt_email',function(){
            var email = $.trim($(this).val()),fullname;
            var posat = email.indexOf('@', 0);
            if(posat > -1){
                fullname = email.substring(0, posat);
            }else{
                fullname = email;
            }
            $('#lightbox').find('#txt_fullname').val(fullname);
        });
    },
    addComment: function(content,fullname,email,type ,reload){

        ArticleComment.fullname = fullname;
        ArticleComment.email = email;
        ArticleComment.type = type;
        Comment.add({
            data: {
                parentid: ArticleComment.params.commentid, // parent id
                objectid: ArticleComment.params.objectid, //article id
                categoryid: ArticleComment.params.cateid, //category of article
                objecttype: ArticleComment.params.objecttype, //type of object: article/photo/video
                content: content, //comment content max 1000 chars
                fullname: fullname, //fullname user max 100 chars
                email: email, //email user
                siteid: ArticleComment.params.siteid //site id
            },
            beforeSend:function(){
                if(type=='act_comment'){
                    $('#comment_post_button').attr("disabled", true);
                    $('#comment_post_button').parent().prepend($('.loading').css({
                        'margin-top':'5px'
                    }).show());
                }else if(type == 'act_reply'){
                    $('#comment_reply_button').attr("disabled", true);
                    $('.loading').insertBefore('#comment_reply_button').show();
                }
            },
            success: function(response){
                if(!response.error){
                    ArticleComment.params.userid = response.userid;
                    if(response.commentid){
                        
                        if(type=='act_comment'){
                            //post comment
                            $('#comment_post_form')[0].reset();

                            ArticleComment.prependComment({
                                commentid: response.commentid,
                                userid: ArticleComment.params.userid,
                                content: content,
                                userlike:[],
                                time: '',
                                fullname:fullname
                            });

                            ArticleComment.totalComment++;

                            $('#total_comment').text(ArticleComment.totalComment);
                            $('#comment_post_form').find('.countdown').text('0/1000');
                            
                        }else if(type == 'act_reply'){
                            $('#comment_reply_form')[0].reset();
                            $('#comment_reply_wrapper').hide();
                            ArticleComment.appendReply('comment_replies_'+ArticleComment.params.commentid, {
                                commentid: response.commentid,
                                userid: ArticleComment.params.userid,
                                content: content,
                                userlike:[],
                                fullname:fullname,
                                time: ''
                            });

                            var od = $('#all_replys_number_'+ArticleComment.params.commentid);
                            var n = od.text()*1;
                            if( n >= 0){
                                n++;
                            }                                
                            od.text(n);
                        }
						
                        Lightbox.showemsg('Gửi bình luận', '<b>Gửi bình luận thành công.</b>', 'Đóng');
						
                        setTimeout(function(){
                            Lightbox.hide();
                            if("undefined" != typeof(reload) && reload){
                                ArticleComment.refreshCurrentPage();
                            }
                        },1000);

                    }
                }else if(response.error == 101){
                    Lightbox.show('login_from','Bạn cần lựa chọn một tài khoản để gửi bình luận', 550);
                    $('#lightbox').find('#if_idp').attr('src',ArticleComment.params.fptid_domain + '/?display=iframe&referersp='+ ArticleComment.params.referersp);                    
                }else if(response.error == 102){
                    Lightbox.showemsg('Thông báo', 'Bạn không được bình luận liên tục.', 'Đóng');
						
                    setTimeout(function(){
                        Lightbox.hide();
                        if("undefined" != typeof(reload) && reload){
                            ArticleComment.refreshCurrentPage();
                        }
                    },1000);


                }
				
            },
            complete: function(){
                FPT_widget_mix();
                $('.loading').hide();
                $('#comment_post_button').attr("disabled", false);
                $('#comment_reply_button').attr("disabled", false);
            },
            error:function(code, msg){}
        });
    },    
    refreshCurrentPage:function(){
        var url		= window.parent.location.href;
        var index	= url.indexOf('#');
        if ( index != -1 ) {
            var hash	= url.substr(index);
            url = url.replace(hash,'');
        }
        window.parent.location	= url;
    },
    likeComment: function(self, id, reload){
        Comment.liketoggle({
            data:{
                commentid: Number(id) ,//comment id
                status:1
            },
            beforeSend:function(){},
            success: function(response){
                if(!response.error){
                    ArticleComment.params.userid = response.userid;

                    if(self){
                        self.removeAttr('href');
                        self.removeClass('cmt-like-toggle');
                        var on  = self.find('.cmt-like-number').text();
                        on = on.replace('(','');
                        on = on.replace(')','');
                        on = Number(on);
                        self.find('.cmt-like-number').text('('+(on+1)+')');
                    }

                    if("undefined" != typeof(reload) && reload){
                        ArticleComment.refreshCurrentPage();
                    }
                    
                }else if(response.error == 101){
                    Lightbox.show('login_from','Bạn cần đăng nhập để thích bình luận', 550);
                    $('#lightbox').find('#if_idp').attr('src',ArticleComment.params.fptid_domain + '/?display=iframe&referersp='+ ArticleComment.params.referersp);                    
                    $('#lightbox').find('.tab2').addClass('active');
                    $('#lightbox').find('.tab1').removeClass('active').off('click');

                    $('#lightbox').find('#fptid_form').show();
                    $('#lightbox').find('#guest_form').hide();
                    return false;
                }
            },
            complete: function(){},
            error:function(code, msg){}
        });
    },
    report: function(id,value){
        var loading = $('<div>').attr({
            'class':'report_bad_loading'
        });

        Comment.reportbad({
            data:{
                commentid: id,//comment id
                message: value, // detail of report
                siteid: ArticleComment.params.siteid
            },
            beforeSend:function(){
                $('#lightbox #bt_report').replaceWith(loading.show());
            },
            success: function(response){
                if(!response.error){
                    ArticleComment.params.userid = response.userid;                    
                    var el = $('.cmt-report-bad[id='+id+']');
                    el.prev().remove();
                    el.remove();
					
                    Lightbox.showemsg('Thông báo vi phạm', 'Cảm ơn thông báo của bạn.', 'Đóng');
                    setTimeout(function(){
                        Lightbox.hide();
                    }, 1500);
                }else{
                    Lightbox.showemsg('Thông báo', 'Gửi thông báo không thành công. Bạn vui lòng thử lại sau.', 'Đóng');
                    setTimeout(function(){
                        Lightbox.hide();
                        ArticleComment.refreshCurrentPage();
                    }, 1500);
                }
            },
            complete: function(){
                loading.remove();                  
            },
            error:function(code, msg){}
        });
    },
    initEvent: function(){
        this.eventChangeTab();
        this.eventGuestSubmit();

        //button post reply
        $(document).on('click','#comment_reply_button',function(){
            ArticleComment.type = 'act_reply';
            
            var content = $.trim($('#comment_reply_content').val());
      
            if(content==""){
                Lightbox.show('empty_comment_from', 'Thông báo', 100);
                return false;
            }
                

            if(ArticleComment.params.userid <= 0){
                Lightbox.show('login_from','Bạn cần lựa chọn một tài khoản để gửi bình luận', 550);
                $('#lightbox').find('#if_idp').attr('src',ArticleComment.params.fptid_domain + '/?display=iframe&referersp='+ ArticleComment.params.referersp);                
                $('#lightbox').find('#txt_email').val(ArticleComment.email);
                $('#lightbox').find('#txt_fullname').val(ArticleComment.fullname);
                return false;
            }
            
            ArticleComment.addComment(content, '', '',ArticleComment.type);

        });

        $(document).on('click','.view_all_reply',function(e){
            e.preventDefault();

            var parentid = this.id;
            var self = $(this);

            var loading = $('.view_all_reply_loading').clone();
            Comment.getallcomment({
                data:{
                    parentid: parentid,// parent comment id, (0: no parent)
                    siteid: ArticleComment.params.siteid, //site id
                    objectid: ArticleComment.params.objectid //article id
                },
                beforeSend:function(){
                    self.hide();
                    loading.insertBefore(self).show();
                },
                success: function(response){
                    if(!response.error){
                        ArticleComment.params.userid = response.data.userid;
                        ArticleComment.renderAllReplies({
                            parentid:parentid,
                            data:response.data
                        });
                    }
                },
                complete: function(){
                    FPT_widget_mix();
                    loading.hide();
                },
                error:function(code, msg){}
            });
        });

        //attach event reply comment
        $(document).on('click', '.show_comment_form', function(){

            //set parent id
            ArticleComment.params.commentid = this.id;

            //$('#comment_reply_wrapper').insertAfter($(this).parent().parent().parent()).show();
            $('#comment_reply_wrapper').insertAfter($('#comment_replies_'+ArticleComment.params.commentid).find('.replys-wrapper')).show();

            $('#comment_reply_content').focus();
        });
        
        //button post comment
        $(document).on('click','#comment_post_button',function(e){
            
            e.preventDefault();
            
            ArticleComment.type = 'act_comment';
            
            var content = $.trim($('#comment_content').val());
            
            if(content =="Hãy nhập ý kiến của bạn về bài viết này..."){
                Lightbox.show('empty_comment_from', 'Thông báo', 100);
                return false;
            }

            if(ArticleComment.params.userid <= 0){                
                Lightbox.show('login_from','Bạn cần lựa chọn một tài khoản để gửi bình luận', 550);
                $('#lightbox').find('#if_idp').attr('src',ArticleComment.params.fptid_domain + '/?display=iframe&referersp='+ ArticleComment.params.referersp);
                $('#lightbox').find('#txt_email').val(ArticleComment.email);
                $('#lightbox').find('#txt_fullname').val(ArticleComment.fullname);
                return false;
            }
            
            ArticleComment.addComment(content, '', '', ArticleComment.type);
        });
        
        //attach event show more comment
        $(document).on('click','#showmore_comment',function(){
		
            var loading = $('.view_all_reply_loading').clone();
			
            loading.insertAfter($(this)).show();
			
            //set new offset
            ArticleComment.params.offset = ArticleComment.params.offset + ArticleComment.params.limit;
            
            //get comment
            ArticleComment.getComment();
        });  
        
        $('#comment_content').focus(function(){
            if($(this).val() == 'Hãy nhập ý kiến của bạn về bài viết này...')
                $(this).val('');
        }).blur(function(){
            if($(this).val()=='')
                $(this).val('Hãy nhập ý kiến của bạn về bài viết này...');
        });   
        
        $(document).on('click','.cmt-like-toggle',function(e){
            e.preventDefault();
            
            var self = $(this);
            ArticleComment.act = 'like';
            ArticleComment.likeid = this.id;
            //var status = Number(this.rel);


            if(ArticleComment.params.userid <= 0){
                Lightbox.show('login_from','Bạn cần đăng nhập để thích bình luận', 550);
                $('#lightbox').find('#if_idp').attr('src',ArticleComment.params.fptid_domain + '/?display=iframe&referersp='+ ArticleComment.params.referersp);                
                $('#lightbox').find('.tab2').addClass('active');
                $('#lightbox').find('.tab1').removeClass('active').off('click');
                $('#lightbox').find('#fptid_form').show();
                $('#lightbox').find('#guest_form').hide();
                return false;
            }

            ArticleComment.likeComment(self, ArticleComment.likeid, false);

            return false;
        });
        
        $(document).on('click','.cmt-report-bad',function(e){
            e.preventDefault();
            ArticleComment.reportid  = Number(this.id);
            Lightbox.show('report_bad','Thông báo vi phạm', 400);
        });

        $(document).on('click','#lightbox #bt_report',function(e){

            var value = $('input[name="reason"]:checked').val();
            if(undefined == value){
                alert('Vui lòng chọn 1 trong 3 thông báo trên.');
                return false;
            }
            ArticleComment.report(ArticleComment.reportid, value);
        });
        
        $(document).on('keyup','#comment_content',function(){
            var val = $(this).val();
            var l = val.length;
            if(l<=1000){
                $(this).prev().text(l + "/1000");
            }else{
                $(this).val(val.substring(0, 1000));                
            }           
        });

        window.loginCallback = function(a, b){
            parent.Lightbox.hide();

            if ("function" == a) {
                eval('parent.' + b + "()");
            }
        }

        window.loginjs = function(){
            var content;
            if(undefined != ArticleComment.type){
                if(ArticleComment.type == 'act_comment'){
                    content = $.trim($('#comment_content').val());
                }else if(ArticleComment.type == 'act_reply'){
                    content = $.trim($('#comment_reply_content').val());
                }

                if(content == "Hãy nhập ý kiến của bạn về bài viết này..."){
                    return false;
                }else{
                    ArticleComment.addComment(content, '', '',ArticleComment.type, true);
                }
            }

            if(undefined != ArticleComment.act && ArticleComment.act == 'like'){
                ArticleComment.likeComment(null, ArticleComment.likeid ,true);
            }

            return false;
        }
    }
};

